package cn.otrue.patienthealthmanager.utils;

import java.io.IOException;

import android.content.Context;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
/**
 * 铃音播放工具类
 * @author zhangwenjun
 *
 */
public class MediaPlayerTools {
	public static MediaPlayer mediaPlayer = null;
	/**
	 * 初始化MediaPlayer
	 * @param context
	 * @param path
	 * @return
	 */
	public  static MediaPlayer initMediaPlayer(Context context, String path) {
		try {
			if (mediaPlayer != null) {
				mediaPlayer.release();
				mediaPlayer = new MediaPlayer();
				if (!"".equals(path)) {
					mediaPlayer.setDataSource(path);
				}else {
					mediaPlayer.setDataSource(context, RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
				}
				mediaPlayer.setAudioStreamType(2);
				mediaPlayer.setLooping(false);
				mediaPlayer.prepare();
			} else {
				mediaPlayer = new MediaPlayer();
				if (!"".equals(path)) {
					mediaPlayer.setDataSource(path);
				}else {
					mediaPlayer.setDataSource(context, RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
				}
				mediaPlayer.setAudioStreamType(2);
				mediaPlayer.setLooping(false);
				mediaPlayer.prepare();
			}
			return mediaPlayer;
		} catch (IOException e) {
			return null;
		}
	}
	/**
	 * 获取铃音总时长
	 * @return
	 */
	public static int getMusicTotalTime(){
		if (mediaPlayer!=null) {
			return mediaPlayer.getDuration();
		}
		return 0;
	}
	/**
	 * 开始播放
	 */
	public static void startPlay(){
		if (mediaPlayer!=null) {
			if (mediaPlayer.isLooping()) {
				mediaPlayer.reset();
			}else {
				mediaPlayer.start();
			}
		}
	}
	/**
	 * 停止播放
	 */
	public static void stopPlay(){
		if (mediaPlayer!=null) {
			if (mediaPlayer.isPlaying()) {
				mediaPlayer.stop();
			}
			mediaPlayer.release();
			mediaPlayer=null;
		}
	}
	/**
	 * 资源回收
	 */
	public static void destory(){
		if (mediaPlayer!=null) {
			mediaPlayer.release();
			mediaPlayer=null;
		}
	}
}
